package com.hzpd.hainan.module.usercenter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hzpd.hainan.R;
import com.hzpd.hainan.app.BaseFragment;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.model.event.LoginSuccessEvent;
import com.hzpd.hainan.model.usercenter.ThirdLoginBean;

import com.hzpd.hainan.model.usercenter.UserEntity;
import com.hzpd.hainan.module.usercenter.UserCenterFragment;


import com.hzpd.hainan.module.usercenter.acticity.BindMobileActivity;
import com.hzpd.hainan.module.usercenter.acticity.LoginActivity;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;


import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/5.
 */

public class LoginFragment extends BaseFragment {
    @BindView(R.id.title_stilte_layout)
    TextView title_stilte_layout;
    @BindView(R.id.account_et_login_fragment)
    EditText account_et_login_fragment;
    @BindView(R.id.pw_et_login_fragment)
    EditText pw_et_login_fragment;
    @BindView(R.id.forget_tv_login_fragment)
    TextView forget_tv_login_fragment;
    @BindView(R.id.btn_login_fragment)
    Button btn_login_fragment;
    @BindView(R.id.tv_login_layout)
    TextView tv_login_layout;
    @BindView(R.id.wxlogintv)
    TextView wxlogintv;
    @BindView(R.id.sinalogintv)
    TextView sinalogintv;
    @BindView(R.id.qqlogintv)
    TextView qqlogintv;
    @BindView(R.id.hasnoaccounttv)
    TextView hasnoaccounttv;
    @BindView(R.id.register_login_fragment)
    TextView register_login_fragment;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 888: {
                    Platform plat = (Platform) msg.obj;
                    PlatformDb platDB = plat.getDb();
                    // 通过DB获取各种数据
                    String token = platDB.getToken();
                    String gender = platDB.getUserGender();
                    String usericon = platDB.getUserIcon();
                    String userid = platDB.getUserId();
                    String username = platDB.getUserName();
                    String userplatform = platDB.getPlatformNname();
                    LogUtils.i("token" + token + " gender:" + gender + " usericon:"
                            + usericon + " userid:" + userid + " username:"
                            + username + " userplatform:" + userplatform);
                    ThirdLoginBean tlb = new ThirdLoginBean(userid, gender,
                            username, usericon, userplatform);
                    thirdLogin(tlb);
                }
                break;
                case 889: {
                    TUtils.toast("登陆失败");
                }
                break;
                case 890: {
                    TUtils.toast("登录取消");
                }
                case 100: {
                    Platform plat = (Platform) msg.obj;
//					LogUtils.i("plat--->"+plat.toString());
                }
                break;
//                case 1: {
//                    if (isThirdLogin.equals("1")) {
//                        login_thirdlogin_Rl.setVisibility(View.VISIBLE);
//                    } else {
//                        login_thirdlogin_Rl.setVisibility(View.GONE);
//                    }
//                }
//                break;
            }
        }
    };

    private void thirdLogin(ThirdLoginBean tlb) {
        Map<String, String> map = new HashMap<>();
        map.put("userid", tlb.getUserid());
        map.put("gender", tlb.getGender());
        map.put("nickname", tlb.getNickname());
        map.put("photo", tlb.getPhoto());
        map.put("third", tlb.getThird());
        LogUtils.e("userid--" + tlb.getUserid());
        LogUtils.e("userid--" + tlb.getGender());
        LogUtils.e("userid--" + tlb.getNickname());
        LogUtils.e("userid--" + tlb.getPhoto());
        LogUtils.e("userid--" + tlb.getThird());
        Factory.provideHttpService().thirdLogin(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("code" + userEntity.code);
                        if ("200".equals(userEntity.code)) {
                            return true;
                        } else {
                            TUtils.toast("账号或密码错误");
                            return false;
                        }

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {

                        LogUtils.e("login_success" + userEntity.data.getStatus());

                        if ("200".equals(userEntity.code)) {
//                            if ("2".equals(userEntity.data.getStatus())) {
                                TUtils.toast("登录成功");
                                LogUtils.e("bind----"+userEntity.data.getStatus());

                                if(userEntity.data.getStatus().equals("1")){
                                    spu.setLogintype("2");
                                }else{
                                    spu.setLogintype("1");
                                }
                            spu.setUser(userEntity.data);
                            Intent intent = new Intent();
                                intent.setAction(UserCenterFragment.ACTION_USER);
                                activity.sendBroadcast(intent);
//                            } else if ("1".equals(userEntity.data.getStatus())) {
//                                Intent intent = new Intent(activity, BindMobileActivity.class);
//                                intent.putExtra("bindid", userEntity.data.getBindid());
//                                startActivity(intent);
//
//                                TUtils.toast("请绑定手机号");
//
//                            }
                            activity.finish();
                        } else {
                            TUtils.toast(userEntity.msg);
                        }


//                            TUtils.toast("登录成功");


                    }
                });

    }

    @Override
    public int setMyContentView() {
        return R.layout.fragment_login;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            title_stilte_layout.setText("登陆");
            account_et_login_fragment.setHint("邮箱帐号或者手机号");
            pw_et_login_fragment.setHint("密码");
            forget_tv_login_fragment.setText("忘记密码");
            btn_login_fragment.setText("登录");
            tv_login_layout.setText("还可以选择以下方式登录");
            wxlogintv.setText("微信帐号登录");
            sinalogintv.setText("新浪账号登录");
            qqlogintv.setText("QQ帐号登录");
            hasnoaccounttv.setVisibility(View.VISIBLE);
            register_login_fragment.setText("立即注册");
        }else{
            title_stilte_layout.setText("ཐོ་འཇུག");
            account_et_login_fragment.setHint("ཡིག་ཟམ་ཡང་ན་ཁ་པར་ཨང་གྲངས།");
            pw_et_login_fragment.setHint("གསང་གྲངས།");
            forget_tv_login_fragment.setText("གསང་གྲངས་བརྗེད་པ།");
            btn_login_fragment.setText("ཐོ་འཇུག");
            tv_login_layout.setText("ཐོ་འཇུག་བྱེད་སྟངས་གཞན།");
            wxlogintv.setText("འཕྲིན་ཕྲན།");
            sinalogintv.setText("པོད་འཕྲིན།");
            qqlogintv.setText("QQ");
            hasnoaccounttv.setVisibility(View.GONE);
            register_login_fragment.setText("ཐོ་འགོད་བྱེད་ས།");
        }

    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @OnClick(R.id.back_stitle_layout)
    public void goback(View v) {
        activity.onBackPressed();
    }

    @OnClick({R.id.btn_login_fragment, R.id.forget_tv_login_fragment, R.id.register_login_fragment})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_login_fragment:

                login();
                break;
            case R.id.forget_tv_login_fragment:
                ((LoginActivity) activity).toFindbackpwdFm();
                break;
            case R.id.register_login_fragment:
                ((LoginActivity) activity).toRehisterFm();
                break;
        }
    }

    @OnClick({R.id.login_qq_login_fragment,
            R.id.login_weibo_login_fragment,
            R.id.login_weixin_login_fragment})
    public void ThirdLogin(View view) {

        Platform platform = null;

        switch (view.getId()) {
            case R.id.login_qq_login_fragment:
                platform = ShareSDK.getPlatform(QQ.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                break;
            case R.id.login_weibo_login_fragment:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                break;
            case R.id.login_weixin_login_fragment:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                if (platform.isAuthValid()) {
                    platform.removeAccount(true);
                }
                platform.authorize();
                break;
        }
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                if (Platform.ACTION_USER_INFOR == i) {
                    Message msg = handler.obtainMessage();
                    msg.what = 888;
                    msg.obj = platform;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                platform.removeAccount(true);
                handler.sendEmptyMessage(889);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                platform.removeAccount(true);
                handler.sendEmptyMessage(890);
            }
        });

        platform.SSOSetting(false);

        platform.showUser(null);// 执行登录，登录后在回调里面获取用户资料
    }

    //登陆
    private void login() {
        String account = account_et_login_fragment.getText().toString().trim();
        String pw = pw_et_login_fragment.getText().toString().trim();
//        if (!MyCommonUtil.isNetworkConnected(activity)) {
//            TUtils.toast("网络异常,请检查网络");
//            return;
//        }
        if (account == null || account.length() <= 0) {
            TUtils.toast("请输入账号");
            return;
        }
        if (pw == null || pw.length() <= 0) {
            TUtils.toast("请输入密码");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("username", account);
        map.put("password", pw);
        Factory.provideHttpService().login(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.i("200--login" + userEntity.code);
//                        if ("200".equals(userEntity.code)){
//                            return true;
//                        }
                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        LogUtils.e("status-----" + userEntity.data.getStatus());
//                        if("2".equals(userEntity.data.getStatus())) {
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("登录成功");
                            LogUtils.e("login_success" + userEntity);
                            spu.setLogintype("1");
                            spu.setUser(userEntity.data);
                            Intent intent = new Intent();
                            intent.setAction(UserCenterFragment.ACTION_USER);
                            activity.sendBroadcast(intent);
                            activity.finish();
                            LoginSuccessEvent event=new LoginSuccessEvent();
                            event.setIslogin(true);
                            EventBus.getDefault().post(event);
                        } else {
                            TUtils.toast(userEntity.msg);
                        }

//                        }else if ("1".equals(userEntity.data.getStatus())){
//                            Intent intent=new Intent(activity,BindMobileActivity.class);
//                            intent.putExtra("bindid",userEntity.data.getBindid());
//                            startActivity(intent);
//                            TUtils.toast("绑定手机号");
//                            activity.finish();
//                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }
}
